﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace IsPic
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public static string getImageType(byte[] data,int dataSize)
        {
            string strResult = "";
            if (dataSize <= 8)
            {
                return strResult;
            }

            //判定是否为JPG文件
            if (data[0] == 0xFF && data[1] == 0xD8 && data[6] == 'E' && data[7] == 'X')
            {
                strResult = "jpg";
                return strResult;
            }

            //判定是否为JPEG文件
            if (data[0] == 0xFF && data[1] == 0xD8 && data[6] == 'J' && data[7] == 'F')
            {
                strResult = "jpeg";
                return strResult;
            }

            //判定是否为BMP文件
            if (data[0] == 'B' && data[1] == 'M' && data[5] == 0x00 && data[6] == 0x00)
            {
                strResult = "bmp";
                return strResult;
            }

            //判断是否是PNG
            if (data[0] == 0x89 && data[1] == 0x50 && data[2] == 0x4e && data[3] == 0x47)
            {
                strResult = "png";
                return strResult;
            }

            //判定是否为gif
            if (data[0] == 'G' && data[1] == 'I' && data[2] == 'F' && data[3] == '8' && data[5] == 'a')
            {
                if (data[6] > 0x20)
                {
                    if (data[7] < 0x20)
                    {
                        strResult = "gif";
                        return strResult;
                    }
                }else{
                    strResult = "gif";
                    return strResult;
                }
            }

            //判定是否为ico
            if (data[0] == 0x00 && data[1] == 0x00 && data[2] == 0x01 && data[3] == 0x00)
            {
                strResult = "ico";
                return strResult;
            }

            return strResult;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFile.ShowDialog();
            string file = openFile.FileName;
            FileStream fs = File.OpenRead(file);
            byte[] arr = new byte[200];
            fs.Read(arr, 0, 100);

            string str = getImageType(arr, 200);
            MessageBox.Show(str);
        }   
    }
}
